const objProToString = Object.prototype.toString;

export function isDate(value) { return objProToString.call(value) === '[object Date]'; }

export function isRegExp(value) { return objProToString.call(value) === '[object RegExp]'; }

export function isNumber(value) { return objProToString.call(value) === '[object Number]'; }

export function isString(value) { return objProToString.call(value) === '[object String]'; }

export function isBoolean(value) { return objProToString.call(value) === '[object Boolean]'; }

export function isObject(value) { return objProToString.call(value) === '[object Object]'; }

export const useResizeObserver = typeof (<any>window).ResizeObserver === 'function';

// 从对象中抓取部分属性生成另一个对象
export function pick(data, extraKeys): any {
  const newData = {};
  if (!isString(extraKeys)) {
    return newData;
  }

  extraKeys = extraKeys.trim().split(/\s+/);

  Object.keys(data).forEach(function (key) {
    if (extraKeys.includes('**') || extraKeys.includes(key)) {
      newData[key] = data[key];
    }
    if (extraKeys.includes('-' + key)) {
      delete newData[key];
    }
  });

  return newData;
}

// 判断一个值是否为空（字符串排除掉空字符）
export function isEmpty(value) {
  if (isString(value)) {
    return value.trim().length === 0;
  }
  return !value;
}


// 升序比较数组元素中某个属性，用于排序
export function compareAsc(arr, propertyName) {
  if ((typeof arr[0][propertyName]) !== 'number') {
    return (object1, object2) => {
      const value1 = object1[propertyName];
      const value2 = object2[propertyName];
      return value1.localeCompare(value2);
    };
  } else {
    return function (object1, object2) {
      const value1 = object1[propertyName];
      const value2 = object2[propertyName];
      return value1 - value2;
    };
  }
}

// 降序比较数组元素中某个属性，用于排序
export function compareDesc(arr, propertyName) {
  if ((typeof arr[0][propertyName]) !== 'number') {
    return (object1, object2) => {
      const value1 = object1[propertyName];
      const value2 = object2[propertyName];
      return value2.localeCompare(value1);
    };
  } else {
    return function (object1, object2) {
      const value1 = object1[propertyName];
      const value2 = object2[propertyName];
      return value2 - value1;
    };
  }
}

// 日期是否在日期范围内
export function dateIsAcrossDateRange(date: any, dateRange: any[]): boolean {

  const sourceDate = new Date(date);
  const startDate = new Date(dateRange[0]);
  const endDate = new Date(dateRange[1]);

  const startDateDifference = sourceDate.setMilliseconds(0) - startDate.setMilliseconds(0);
  const endDateDifference = sourceDate.setMilliseconds(0) - endDate.setMilliseconds(0);
  if (!dateRange || dateRange.length !== 2 || !isDate(sourceDate) || !isDate(startDate) || !isDate(endDate)) {
    return false;
  } else {
    return startDateDifference >= 0 && endDateDifference <= 0;
  }

}
